/*
 * @(#)GetWorkflowProgressAttachmentServlet.java
 *
 * Copyright (c) 2003 DCIVision Ltd
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of DCIVision
 * Ltd ("Confidential Information").  You shall not disclose such Confidential
 * Information and shall use it only in accordance with the terms of the license
 * agreement you entered into with DCIVision Ltd.
 */
package com.dcivision.form.web;

import java.io.IOException;
import java.sql.Connection;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.dcivision.dms.core.FileDownloader;
import com.dcivision.framework.ApplicationException;
import com.dcivision.framework.DataSourceFactory;
import com.dcivision.framework.HTTPUtility;
import com.dcivision.framework.SystemParameterConstant;
import com.dcivision.framework.SystemParameterFactory;
import com.dcivision.framework.Utility;

/**
 * @author           Lun Au
 * @company          DCIVision Limited
 * @creation date    2005/1/7
 * @version          $Revision: 1.1.8.2 $
 */
public class ShowFormImageServlet extends HttpServlet {

  protected Log log = LogFactory.getLog(this.getClass().getName());

  public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    String fileName = request.getPathInfo();
    String filePath = SystemParameterFactory.getSystemParameter(SystemParameterConstant.FORM_ATTACHMENT_PHYSICAL_PATH)+fileName;
    Connection conn = null;

    // TODO: Check permission if the requestor is allowed to download the attachment

    try{
      // Get the database connection.
      conn = DataSourceFactory.getConnection();
    if (!Utility.isEmpty(filePath) && !"null".equals(filePath)){
        String contentType=HTTPUtility.getContentType(filePath);
        java.io.BufferedInputStream inputStream = new java.io.BufferedInputStream(new java.io.FileInputStream(filePath));
        if (contentType != null) {
          FileDownloader fd = new FileDownloader();
          fd.setFileName(fileName);
          fd.setContentType(contentType);
          fd.setInputStream(inputStream);
          fd.setRequest(request);
          fd.setResponse(response);
          fd.operate();
        }
      }
    } catch (ApplicationException ae){
      log.fatal(ae.getMessage(), ae);
    } catch (Exception e) {
      log.fatal(e.getMessage(), e);
    } finally {
      try { conn.close(); } catch (Exception ignore) {} finally { conn = null; }
    }
  }

}
